package com.htfyun;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.OwnerSurfaceView;
import android.view.OwnerSurfaceView;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.htfyun.database.DaoSession;
import com.htfyun.database.GreenDaoManager;
import com.htfyun.database.PWNote;
import com.htfyun.database.PWNoteDao;
import com.htfyun.database.PngName;
import com.htfyun.database.PngNameDao;
import com.htfyun.fragment.postil.HtfyunPWFragment;
import com.htfyun.utils.DebugLog;
import com.htfyun.utils.DisplayUtil;
import com.squareup.picasso.Picasso;
import com.yinghe.whiteboardlib.bean.Image;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.ViewsById;
import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import group.pals.android.lib.ui.filechooser.utils.ActivityCompat;

/**
 * Created by sst on 2017/12/30.
 */
@EActivity(R.layout.htfyun_activity_pw)
public class PWActivity extends AppCompatActivity {

    private Context mContext;
    private PopupWindow popupWindowShape;
    private PopupWindow popupWindowBackground;
    private PopupWindow popupWindowLineWidth;
    
    @ViewById
    ImageView imgPWShape;
    @ViewById
    ImageView imgPWBackground;
    @ViewById
    ImageView imgPWLineWidth;

    @ViewById
    ImageView surfaceView_bg_ImageView;

    @ViewById
    OwnerSurfaceView pwdraw_surface_view;

    @ViewById
    ImageView toolbarLeftImg;

    @ViewById
    ImageView imgPWPngAdd;

    @ViewById
    ImageView imgPWPngRemove;

    @ViewById
    ImageView imgPWPngPrevious;

    @ViewById
    ImageView imgPWPngNext;

    @ViewById
    TextView txtPWPngPercent;


    private List<PngName> pngNameList;
    private int pngNameIndex = 0;
    private PWNote pwNote;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this;
        loadPWNote(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        loadPWNote(intent);

    }

    private void loadPWNote(Intent intent) {
        DaoSession daoSession = GreenDaoManager.INSTANCE.getDaoSession();
        PWNoteDao pwNoteDao = daoSession.getPWNoteDao();
        PngNameDao pngNameDao = daoSession.getPngNameDao();

        long id = intent.getLongExtra("id", -1);
        pwNote = pwNoteDao.load(id);
        if (pwNote == null) {
            finish();

            DebugLog.e("pwNote is null, please check");
            return;
        }

        pngNameList = pngNameDao.queryBuilder()
                .where(PngNameDao.Properties.OtherUuid.eq(pwNote.getUuid())).list();

        if (pngNameList.isEmpty()) {
            PngName pngName = new PngName();
            pngName.setDate(new Date());
            pngName.setOtherUuid(pwNote.getUuid());
            pngName.setUuid(UUID.randomUUID().toString());
            pngName.setPngName(pngName.getUuid() + ".png");

            pngNameDao.insert(pngName);

            pngNameList.add(pngName);
        }

        pngNameIndex = pngNameList.size() - 1;

    }

    @AfterViews
    void afterViews() {

        initShape();
        initBackground();
        initLineWidth();
        
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (pngNameIndex >= pngNameList.size()) {
            pngNameIndex = pngNameList.size() - 1;
        }

        pwdraw_surface_view.setVisibility(View.VISIBLE);
        surfaceView_bg_ImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

        pwdraw_surface_view.setDrawObjectType(OwnerSurfaceView.DRAW_OBJ_RANDOM);

        updateTxtPWPngPercent();
        updatePWDrawSurfaceView();


//        pwdraw_surface_view.addOnSurfaceDestroyListener(new OwnerSurfaceView.OnSurfaceDestroyListener() {
//            @Override
//            public void onDestroy(Surface surface, Rect rect) {
//                
//                saveBmp();
//                
//                DebugLog.e("onDestroy owner surface view");
//                
//                mContext.sendBroadcast(new Intent(Constants.ACTION_SAVE_BMP));
//                
//            }
//        });
      
    }

    @Override
    protected void onPause() {
        super.onPause();

        saveBmp();
    }

    @Override
    protected void onStop() {
        super.onStop();

        
    }
    
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Click(R.id.toolbarLeftImg)
    void clickOnToolbarLeftImg() {
        saveBmp();
        android.support.v4.app.ActivityCompat.finishAfterTransition(this);
    }

    @Click(R.id.imgPWShape)
    void clickOnImgPWShape() {

        showPopupWindow(popupWindowShape);
        popupWindowShape.showAsDropDown(imgPWShape, 0, 0);

    }

    @Click(R.id.imgPWBackground)
    void clickOnImgPWBackground() {

        showPopupWindow(popupWindowBackground);
        popupWindowBackground.showAsDropDown(imgPWBackground, 0, 0);

    }

    @Click(R.id.imgPWLineWidth)
    void clickOnImgPWLineWidth() {

        showPopupWindow(popupWindowLineWidth);
        popupWindowLineWidth.showAsDropDown(imgPWLineWidth, 0, 0);

    }

    @Click(R.id.imgPWUndo)
    void clickOnImgPWUndo() {

        pwdraw_surface_view.unDo();

    }

    @Click(R.id.imgPWSave)
    void onClick_imgPWSave() {
        
        saveBmp();
    }


    @Click(R.id.imgPWPngAdd)
    void clickOnImgPWPngAdd() {
        
        DaoSession daoSession = GreenDaoManager.INSTANCE.getDaoSession();
        PngNameDao pngNameDao = daoSession.getPngNameDao();

        PngName pngName = new PngName();
        pngName.setDate(new Date());
        pngName.setOtherUuid(pwNote.getUuid());
        pngName.setUuid(UUID.randomUUID().toString());
        pngName.setPngName(pngName.getUuid() + ".png");

        pngNameDao.insert(pngName);

        pngNameList.add(pngName);

        pngNameIndex = pngNameList.size() - 1;

        updateTxtPWPngPercent();
        
        updatePWDrawSurfaceView();

    }

    @Click(R.id.imgPWPngPrevious)
    void clickOnImgPWPngPrevious() {

        if (pngNameIndex <= 0) {
            return;
        }
        pngNameIndex--;
        
        updateTxtPWPngPercent();
        updatePWDrawSurfaceView();

    }

    @Click(R.id.imgPWPngNext)
    void clickOnImgPWPngNext() {

        if (pngNameIndex >= pngNameList.size()) {
            return;
        }
        pngNameIndex++;

        updateTxtPWPngPercent();
        updatePWDrawSurfaceView();

    }

    private void updatePWDrawSurfaceView() {

        if (pngNameIndex >= pngNameList.size()) {
            return;
        }

        saveBmp();
        
        pwdraw_surface_view.clearContent(null, true, true);
        
        Bitmap bmp = BitmapFactory.decodeFile(Constants.toPngPath(pngNameList.get(pngNameIndex).getPngName()));
        if (bmp != null) {
            
            pwdraw_surface_view.setPWBitmap(bmp);
        }

        pwdraw_surface_view.setHostView(surfaceView_bg_ImageView);//, Constants.toPngPath(pngNameList.get(pngNameIndex).getPngName()) ,false);
        pwdraw_surface_view.setLoadFilePath(Constants.toPngPath(pngNameList.get(pngNameIndex).getPngName()), true);
    }

    private void updateTxtPWPngPercent(){

        txtPWPngPercent.setText(getResources().getString(R.string.base_page_number_percent, pngNameIndex + 1, pngNameList.size()));

        imgPWPngPrevious.setVisibility(View.VISIBLE);
        imgPWPngNext.setVisibility(View.VISIBLE);
        
        if (pngNameIndex == 0) {
            
            imgPWPngPrevious.setVisibility(View.INVISIBLE);
        }

        if (pngNameIndex == pngNameList.size() - 1) {
            
            imgPWPngNext.setVisibility(View.INVISIBLE);

        }
    }

    private void saveBmp() {
      
        pwdraw_surface_view.saveBitmap(false, null);

        if (pngNameIndex >= pngNameList.size()) {
            return;
        }

        String path = Constants.toPngPath(pngNameList.get(pngNameIndex).getPngName());
        Bitmap bmp = pwdraw_surface_view.getPureWriteBitmap();

        if (bmp != null) {
            DebugLog.e("saveBmp bmp = " + bmp + ", path = " + path);

//            Matrix matrix = new Matrix();
//            matrix.postScale(0.2f, 0.2f);
//            // 得到新的图片  
//            Bitmap newbm = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix,
//                    true);
//
//            CachePngToBmpManager.INSTANCE.putBitmap(path, newbm);
            
            CachePngToBmpManager.INSTANCE.putBitmap(path, bmp.copy(Bitmap.Config.ARGB_8888, false));
            
        }
       
    }
    

    private PopupWindow initPopupWindow(Context context, @LayoutRes int layoutRes) {
        
        PopupWindow pw = new PopupWindow(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity
                .LAYOUT_INFLATER_SERVICE);

        pw.setContentView(inflater.inflate(layoutRes, null));//设置主体布局
        pw.setFocusable(true);
        pw.setAnimationStyle(0);

        pw.setWidth(DisplayUtil.getScreenWidth(context));//宽度200dp
        int height = getResources().getDimensionPixelSize(R.dimen.activity_pw_func_main_height);
        pw.setHeight(height + 10);

        return pw;

    }

    private void initLineWidth() {
        popupWindowLineWidth = initPopupWindow(this, R.layout.htfyun_popup_pw_pen_width);
        View view = popupWindowLineWidth.getContentView();

        final View width0 = view.findViewById(R.id.einkdraw_pen_width_0);
        width0.setTag(OwnerSurfaceView.MIN_PEN_WIDTH_PIXEL);
        width0.setOnClickListener(clickListenerLineWidth);
        
        final View width1 = view.findViewById(R.id.einkdraw_pen_width_1);
        width1.setTag(OwnerSurfaceView.MIN_PEN_WIDTH_PIXEL + 1);
        width1.setOnClickListener(clickListenerLineWidth);

        final View width2 = view.findViewById(R.id.einkdraw_pen_width_2);
        width2.setTag(OwnerSurfaceView.MIN_PEN_WIDTH_PIXEL + 2);
        width2.setOnClickListener(clickListenerLineWidth);

        final View width3 = view.findViewById(R.id.einkdraw_pen_width_3);
        width3.setTag(OwnerSurfaceView.MIN_PEN_WIDTH_PIXEL + 3);
        width3.setOnClickListener(clickListenerLineWidth);

        final View width4 = view.findViewById(R.id.einkdraw_pen_width_4);
        width4.setTag(OwnerSurfaceView.MIN_PEN_WIDTH_PIXEL + 4);
        width4.setOnClickListener(clickListenerLineWidth);
    }

    private View.OnClickListener clickListenerLineWidth = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pwdraw_surface_view.setPenSettingWidth((int)v.getTag());
            popupWindowLineWidth.dismiss();
        }
    };
    
    private void initBackground() {
        popupWindowBackground = initPopupWindow(this, R.layout.htfyun_popup_pw_background);

        View view = popupWindowBackground.getContentView();

        final View bg_none = view.findViewById(R.id.einkdraw_bg_none);
        bg_none.setTag(OwnerSurfaceView.WT_TYPE_NONE);
        bg_none.setOnClickListener(clickListenerBackground);

        final View bg_intersected = view.findViewById(R.id.einkdraw_bg_intersected);
        bg_intersected.setTag(OwnerSurfaceView.WT_TYPE_INTERSECTED);
        bg_intersected.setOnClickListener(clickListenerBackground);

        final View bg_linefigure = view.findViewById(R.id.einkdraw_bg_linefigure);
        bg_linefigure.setTag(OwnerSurfaceView.WT_TYPE_LINEFIGURE);
        bg_linefigure.setOnClickListener(clickListenerBackground);

        final View bg_matts = view.findViewById(R.id.einkdraw_bg_matts);
        bg_matts.setTag(OwnerSurfaceView.WT_TYPE_MATTS);
        bg_matts.setOnClickListener(clickListenerBackground);
      
    }


    private View.OnClickListener clickListenerBackground = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int wtType = (int) v.getTag();
            int dpSize = 0;//OwnerSurfaceView.WM_DEFAULT_UNIT_SIZE_DP;
            if (wtType == OwnerSurfaceView.WT_TYPE_LINEFIGURE) {
                dpSize = 80;
            } else if (wtType == OwnerSurfaceView.WT_TYPE_MATTS) {
                dpSize = 100;
            } else if (wtType == OwnerSurfaceView.WT_TYPE_INTERSECTED) {
                dpSize = 120;
            }
            pwdraw_surface_view.setBackGroupMatts((int)v.getTag(), dpSize);
            popupWindowBackground.dismiss();
        }
    };

    private void initShape() {
        popupWindowShape = initPopupWindow(this, R.layout.htfyun_popup_pw_shape);

        View view = popupWindowShape.getContentView();

        final View obj_pw = view.findViewById(R.id.einkdraw_obj_pw);
        obj_pw.setTag(OwnerSurfaceView.DRAW_OBJ_RANDOM);

        obj_pw.setOnClickListener(clickListenerShape);

        final View obj_line = view.findViewById(R.id.einkdraw_obj_line);
        obj_line.setTag(OwnerSurfaceView.DRAW_OBJ_LINE);
        obj_line.setOnClickListener(clickListenerShape);

        final View obj_circle = view.findViewById(R.id.einkdraw_obj_circle);
        obj_circle.setTag(OwnerSurfaceView.DRAW_OBJ_CIRCLE);
        obj_circle.setOnClickListener(clickListenerShape);

        final View obj_rect = view.findViewById(R.id.einkdraw_obj_rect);
        obj_rect.setTag(OwnerSurfaceView.DRAW_OBJ_RECTANGLE);
        obj_rect.setOnClickListener(clickListenerShape);

        final View obj_triangle = view.findViewById(R.id.einkdraw_obj_triangle);
        obj_triangle.setTag(OwnerSurfaceView.DRAW_OBJ_TRIANGLE);
        obj_triangle.setOnClickListener(clickListenerShape);

    }
   
    
    private View.OnClickListener clickListenerShape = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pwdraw_surface_view.setDrawObjectType((int)v.getTag());
            popupWindowShape.dismiss();
        }
    };

    private void showPopupWindow(PopupWindow popupWindow) {


        int objType = -1;//pwdraw_surface_view.getDrawObjectType();

        if (popupWindow == popupWindowShape) {
            objType = pwdraw_surface_view.getDrawObjectType();
        } else if (popupWindow == popupWindowBackground) {
            objType = pwdraw_surface_view.getBackGroundMattsType();
        } else if (popupWindow == popupWindowLineWidth) {
            objType = pwdraw_surface_view.getPenSettingWidth();
        } else {
            
            return;
        } 
        
        ViewGroup viewGroup = (ViewGroup)popupWindow.getContentView();

        for (int i = 0; i < viewGroup.getChildCount(); i ++) {
            View view = viewGroup.getChildAt(i);
            if (view instanceof ViewGroup) {
                ViewGroup childGroup = (ViewGroup) view;
                for (int j = 0; j < childGroup.getChildCount(); j++) {
                    View childView = childGroup.getChildAt(j);
                    if (!(childView instanceof ImageView) 
                            && view.getTag() != null 
                            && (view.getTag() instanceof  Integer)) {
                        childView.setVisibility((objType == (int) view.getTag()) ? View.VISIBLE : View.INVISIBLE);
                    }
                }
            }
        }

    }
  
}
